package com.akk.utils;

import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtil {

    /**
     * 将文件写入到指定目录
     * @param path 文件路径
     * @param fileName 文件名
     * @param file    文件
     * @return boolean 是否写入成功
     * */
    public static boolean writeFileToPath(String path, String fileName, MultipartFile file){
        File file1 = null;
        try {
            file1 = ResourceUtils.getFile(path+fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }
        if (!file1.exists())
            file1.getParentFile().mkdirs();
        try {
            FileOutputStream outputStream = new FileOutputStream(file1);
            outputStream.write(file.getBytes());
            outputStream.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取文件后缀格式
     * @param fileName 文件名称
     * @return 文件后缀名
     * */
    public static String getFilePostfix(String fileName){
        if (fileName == null || fileName.equals("")){
            return "";
        }
        if (fileName.contains(".")){
            return fileName.substring(fileName.lastIndexOf(".") + 1,fileName.length());
        }
        return "";
    }

    public static boolean isImagePngJpg(String fileName){
        String filePost = getFilePostfix(fileName);
        if (filePost.length() > 0){
            if (filePost.equals("png") || filePost.equals("jpg")||filePost.equals("PNG") || filePost.equals("JPG")|| filePost.equals("JPEG")||filePost.equals("jpeg"))
                return true;
        }
        return false;
    }

}
